<template>
  <div class="bg">


    <div style="background-color: white;padding: 10px;margin-top: 10px;margin-right: 10px;">
      <el-input
        clearable
        placeholder="请输入事件名称"
        prefix-icon="el-icon-search"
        size="small"
        style="width: 300px"
        v-model="eventName"
      />

      <el-button @click="handleAdd" v-hasPermi="['event:add']" icon="el-icon-plus" style="margin-left: 10px"
                 type="text">新建事件
      </el-button>


    </div>


    <div style="background-color: white; min-height: 760px;margin-top: 10px;position: relative">

      <el-row :gutter="10">
        <el-col :span="8" v-for="(item, index) in computedEventsWithStatistics" :key="index">

          <div class="ant-card-bordered">
            <div class="case-header">
              <div class="top-bar">
              </div>
              <div style="margin: 5px 0;font-weight: 500;font-size: 18px;">
                {{item.eventTitle}}
              </div>
              <div style="color: #999;">
                {{item.startTime}}至{{item.endTime}}
              </div>

            </div>
            <div class="ant-card-body">
              <div class="case-body cur-p ng-star-inserted">
                <div class="case-brief">
                  <div>
                    <span class="case-brief-content">在{{item.startTime}}-{{item.endTime}}，【{{item.eventTitle}}】事件中，共有{{item.totalAuthor}}用户发布了{{item.totalArticle}}条相关信息，网民对此事件表达最多的是{{item.emotion}}情绪，占比为{{item.proportion}}%。</span>
                  </div>
                </div>
              </div>
              <div class="case-footer ng-star-inserted">
                <span class="ng-star-inserted">
                  相关舆论：{{item.totalArticle}}条
                </span>
                <span class="color_main"
                      @click="goToViewData(item)"
                >数据图表
                </span>
                <span class="color_main"
                      @click="handleUpdate(item)"
                      v-hasPermi="['event:edit']"
                >修改
                </span>
                <span class="color_main"
                      @click="handleDelete(item)"
                      v-hasPermi="['event:remove']"
                >删除
                </span>
                <span class="color_main" @click="handleDetail(item)">查看 &gt;&gt;</span>
              </div>
            </div>

          </div>

        </el-col>

      </el-row>


      <pagination
        style="position: absolute;bottom: 10px;right: 10px"
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

    </div>


  </div>
</template>

<script>
  import {getEvents, delEvents, listEventsAll} from "@/api/system/event";
  import axios from 'axios';

  export default {
    name: "Events",
    components: {},
    data() {
      return {
        // 遮罩层
        loading: true,
        // 总条数
        total: 0,
        // 事件表格数据
        eventsList: [],
        eventName: null,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 6,
          createdTime: null,
          startTime: null,
          endTime: null,
          eventTitle: null,
          useTemplate: null,
          userId: null,
          topState: null,
          eventState: null,
          searchArea: null,
          relatedWords: null,
          opinionWords: null,
          exclusionWords: null,
          incidentType: null,
          incidentSubject: null
        },
        // 表单参数
        form: {},
        computedEventsWithStatistics: []
      };
    },
    watch: {
      // 根据名称筛选部门树
      eventName(val) {
        this.queryParams.eventTitle = val
        this.getList()
      }
    },
    created() {
      this.getList();
    },

    methods: {
      /** 查询事件列表 */
      getList() {
        this.loading = true;
        listEventsAll(this.queryParams).then(response => {
          this.eventsList = response.rows;
          this.total = response.total;
          this.loading = false;
          this.getComputedEventsWithStatistics()
        });
      },
      async getComputedEventsWithStatistics() {
        try {
          // 创建一个Promise数组
          const promises = this.eventsList.map(async (event) => {
            try {
              const nameResponse = await axios.get(process.env.VUE_APP_BASE_API + `/system/events/getEventSummary/${event.eventId}`);
              // 构造新的event对象，包含原始event和统计数据
              const res = {
                ...event,
                totalAuthor: nameResponse.data.data.totalAuthor,
                totalArticle: nameResponse.data.data.totalArticle,
                totalPositive: nameResponse.data.data.totalPositive,
                totalNegative: nameResponse.data.data.totalNegative,
                totalNeutral: nameResponse.data.data.totalNeutral,
                emotion: nameResponse.data.data.emotion,
                proportion: nameResponse.data.data.proportion,
              };
              // 这里不再需要console.log，但如果你需要调试可以保留
              return res; // 返回修改后的event对象
            } catch (error) {
              console.error(`Error fetching statistics for event ${event.eventId}:`, error);
              return {...event, statisticsError: true};
            }
          });

          // 使用Promise.all等待所有异步操作完成，并收集结果
          this.computedEventsWithStatistics = await Promise.all(promises);
          console.log("eventsWithStatistics:", JSON.stringify(this.computedEventsWithStatistics));

        } catch (error) {
          // 如果在Promise.all外部捕获到错误（例如，在map函数调用之前），则抛出或处理错误
          console.error('Error fetching events with statistics:', error);
          throw error; // 或者返回一个空数组或其他默认值
        }
      },

      // 表单重置
      reset() {
        this.form = {
          eventId: null,
          createdTime: null,
          startTime: null,
          endTime: null,
          eventTitle: null,
          useTemplate: null,
          userId: null,
          topState: null,
          eventState: null,
          searchArea: null,
          relatedWords: null,
          opinionWords: null,
          exclusionWords: null,
          incidentType: null,
          incidentSubject: null
        };
        this.resetForm("form");
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.$router.push({path: '/event/create'});
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const eventId = row.eventId
        getEvents(eventId).then(response => {
          this.form = response.data;
          this.$router.push({path: '/event/create', query: this.form});
        });
      },

      /** 删除按钮操作 */
      handleDelete(row) {
        const eventIds = row.eventId
        this.$confirm('是否确认删除事件编号为"' + eventIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delEvents(eventIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },

      handleDetail(row) {
        const params = {
          eventId: row.eventId,
          eventTitle: row.eventTitle,
          relatedWords: row.relatedWords,
          startTime: row.startTime,
          endTime: row.endTime,
        }
        this.$router.push({path: '/event/detail', query: params});
      },
      goToViewData(row) {
        const params = {
          eventId: row.eventId,
          eventTitle: row.eventTitle,
          relatedWords: row.relatedWords,
          startTime: row.startTime,
          endTime: row.endTime,
        }
        this.$router.push({path: '/event/data', query: params});
      }

    }
  };
</script>


<style scoped lang="scss">
  .bg {
    background-color: #eeeeee;
    height: 100%;
  }

  .top-bar {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 5px;
    background: linear-gradient(90deg, #25bce1, #2a91c9);
    border-top-left-radius: 3px;
    border-top-right-radius: 3px;
  }

  .case-header {
    position: relative;
    height: 100px;
    padding: 20px;
    color: #000;
    text-align: center;
    background-color: #f4fafd;
  }

  .case-footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 49px;
    padding: 0 20px;
    color: #999;
    border-top: 1px solid #e7e7e7;
    cursor: pointer;
  }

  .color_main, .hover_color_main:hover {
    color: #3fc3e3;
  }

  .case-body {
    min-height: 180px;
    padding: 15px;
  }

  .cur-p {
    cursor: pointer;
  }

  .case-brief-content {
    color: #333;
    font-size: 15px;
    line-height: 27px;
  }

  .ant-card-bordered {
    margin: 10px;
    border: 1px solid #f0f0f0;
  }
</style>
